import React, { useRef, useState } from "react";
import { chatReport, chatSimpleChat, chatStreamChat } from "../api";
import { fetchEventSource } from "@microsoft/fetch-event-source";
import Markdown from "react-markdown";
import remarkGfm from "remark-gfm";

interface Message {
  role: "user" | "bot";
  content: string;
}

const ChatClient: React.FC = () => {
  const [messages, setMessages] = useState<Message[]>([
    { role: "bot" as const, content: "你好，我是聊天机器人，有什么可以帮你？" },
  ]);
  const [input, setInput] = useState("");
  const [model, setModel] = useState("deepseek-r1:8b");
  const [platform, setPlatform] = useState("qianfan");
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const fetchSimpleChat = async (input: string) => {
    try {
      const res = await chatSimpleChat(input);
      setMessages((msgs) => [
        ...msgs,
        { role: "bot" as const, content: res.data },
      ]);
    } catch (error) {
      console.error(error);
      setMessages((msgs) => [
        ...msgs,
        { role: "bot" as const, content: "服务器错误，请稍后再试" },
      ]);
    }
  };

  const fetchStreamChat = (input: string, newMsg: Message[]) => {
    let reply = "";
    chatStreamChat(input, undefined, (messages) => {
      reply += messages;

      setMessages([
        ...newMsg,
        {
          role: "bot" as const,
          content: reply,
        },
      ]);
    });
  };

  const handleSend = async () => {
    if (!input.trim()) return;
    const newMessages = [
      ...messages,
      { role: "user" as const, content: input },
    ];
    setMessages(newMessages);
    setInput("");
    // 发送请求
    // fetchSimpleChat(input);
    fetchStreamChat(input, newMessages);
  };

  const handleReport = async () => {
    const res = await chatReport();
    console.log(res, "res>>>");
  };

  React.useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter" && !e.nativeEvent.isComposing) {
      handleSend();
    }
  };

  return (
    <div className="chat-root">
      <div className="chat-messages">
        {messages.map((msg, idx) => (
          <div
            key={idx}
            className={
              msg.role === "user" ? "chat-bubble user" : "chat-bubble bot"
            }
          >
            <Markdown remarkPlugins={[remarkGfm]}>{msg.content}</Markdown>
          </div>
        ))}
        <div ref={messagesEndRef} />
      </div>
      <div className="chat-input-container">
        <div className="chat-input-bar">
          {/*   <select value={platform} onChange={(e) => setPlatform(e.target.value)}>
            <option value="qianfan">Qianfan</option>
            <option value="ollama">Ollama</option>
          </select> */}
          <select value={model} onChange={(e) => setModel(e.target.value)}>
            <option value="deepseek-r1:8b">deepseek-r1</option>
          </select>
        </div>
        <div className="chat-input-bar">
          <input
            type="text"
            placeholder="请输入内容..."
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={handleKeyDown}
          />
          <button onClick={handleSend}>发送</button>
          <button onClick={handleReport}>报告</button>
        </div>
      </div>
    </div>
  );
};

export default ChatClient;
